/***
	Copyright (c) 2008-2009 Jesse Banet, Feanil J. Patel, and Roberto C. Serrano
	
	Licensed under the Apache License, Version 2.0 (the "License"); you may
	not use this file except in compliance with the License. You may obtain
	a copy of the License at
		http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

package com.bikerolas;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

//public class Scream extends Activity {
public class Fling extends Activity {

	public static final String MYPREFS = "screamSharedPrefs";
	public Button btn = null;
	private boolean runAtBoot=false;  
	private boolean serviceIsRunning = false;
	private boolean firstRunWarning = true;
//	private boolean wakeLock = false;
	private Intent svc = null;
    AlertDialog.Builder builder = null;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Set it so that when you are in this application
        // the volume controls change the media volume not
        // the ringer volume.
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        
        loadPrefs();
        
        svc = new Intent(this, FlingService.class);
        
        btn=(Button)findViewById(R.id.start);      
        if (!serviceIsRunning){     	
    		btn.setText("Start the Fling Service");
        }else{
        	
        	//It appears that there is no good way of checking
        	// to see if the service hasn't been killed by the OS
        	// , so to avoid crashing the app we have to bind
        	// the App to the service by starting it.
        	_startSvc();
                        
    		btn.setText("Stop the Fling Service");	    
        }
        btn.setOnClickListener(new View.OnClickListener() {
	        	public void onClick(View v){
	        		//Should we make sure is running before we try?	        		
	        		svcButtonClicked();
	        	}
	    });        

		
        CheckBox autoBoot = (CheckBox)findViewById(R.id.autoBoot);
       	autoBoot.setChecked(runAtBoot);
       	autoBoot.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v){
        		runAtBoot = !runAtBoot;  
//                Log.d("Scream", "runAtBoot=" + runAtBoot);        		
        		savePrefs();
        	}
        });    	
       	
//       	WakeLock doesn't seem to work at all, so I am taking it out for now RCS

//        CheckBox wakeLckChk = (CheckBox)findViewById(R.id.wakeLock);
//        wakeLckChk.setChecked(wakeLock);
//        wakeLckChk.setOnClickListener(new View.OnClickListener() {
//        	public void onClick(View v){
//
//        		// This is really ugly, but in order for the
//        		// change to take effect right away, we need
//        		// to stop and start the service right away
//        		if (serviceIsRunning){
//		    		_stopSvc();
//	        		wakeLock = !wakeLock;     		
//	        		savePrefs();
//		    		_startSvc();
//        		} else {
//	        		wakeLock = !wakeLock;     		
//	        		savePrefs();       			
//        		}
//        	}
//        });
       	
       	builder = new AlertDialog.Builder(this);
	
        if (firstRunWarning) {
    		builder.setMessage("The developers of Fling are not responsable for any damage that may occur to the phone while using Fling.  The user, and only the user, is respossable for any possible damage done to the phone while Fling is in use. Do you agree to use this Application at your own risk?")
    		       .setCancelable(false)
    		       .setNegativeButton("Close", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
   		          			firstRunWarning = true;
	   		         		savePrefs();
    		                finish();
    		           }
    		       })
    		       .setPositiveButton("Accept Risk", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		          		firstRunWarning = false;
    		        		savePrefs();
    		                dialog.cancel();
    		           }
    		       });
    		builder.create().show();   
       	}

        Button btnWarning = (Button)findViewById(R.id.flingLogo);
        
        btnWarning.setOnClickListener(new View.OnClickListener(){
        		public void onClick(View v){
            		builder.setMessage("The developers of Fling are not responsable for any damage that may occur to the phone while using Fling.  The user, and only the user, is respossable for any possible damage done to the phone while Fling is in use. Do you agree to use this Application at your own risk?")
     		       .setCancelable(false)
     		       .setPositiveButton("Accept Risk", new DialogInterface.OnClickListener() {
     		           public void onClick(DialogInterface dialog, int id) {
     		          		firstRunWarning = false;
     		        		savePrefs();
     		                dialog.cancel();
     		           }

     		       });
   		          builder.create().show();
        		}
        });
    }
    
    public void svcButtonClicked(){
    	loadPrefs();
    	
//        Log.d("Scream", "Refreshing layout buttons, serviceIsRunning=" + serviceIsRunning);   

        //if (bindService(svc, conn, Context.BIND_AUTO_CREATE)){
        if (!serviceIsRunning){
    		_startSvc();   	
	    } else {	    	
    		_stopSvc();      
        }                          	
    }
    
    @Override 
    protected void onDestroy() {
    	  super.onDestroy();
    }

    
    //-----------------------------
    //  Application menu
	//------------------------------
    
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit Prefs")
//				.setIcon(R.drawable.misc)
//				.setAlphabeticShortcut('e');
//		menu.add(Menu.NONE, CLOSE_ID, Menu.NONE, "Close")
//				.setIcon(R.drawable.eject)
//				.setAlphabeticShortcut('c');
//
//		return(super.onCreateOptionsMenu(menu));
//	}
//
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		//	case EDIT_ID:
//		//		//startActivity(new Intent(this, EditPreferences.class));
//		//		return(true);
//				
//			case CLOSE_ID:
//				finish();
//				return(true);
//		}
//
//		return(super.onOptionsItemSelected(item));
//	}

    //-----------------------------
    //  Save and restored preferences
	//------------------------------	
	
	protected void savePrefs(){
		SharedPreferences mySharedPrefs = getSharedPreferences(MYPREFS, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mySharedPrefs.edit();
		
		editor.putBoolean("runAtBoot", runAtBoot);	
		editor.putBoolean("serviceIsRunning", serviceIsRunning);
		editor.putBoolean("firstRunWarning", firstRunWarning);
//		editor.putBoolean("wakeLock", wakeLock);
		editor.commit();
	}
	
	protected void loadPrefs(){
		SharedPreferences mySharedPrefs = getSharedPreferences(MYPREFS, Activity.MODE_PRIVATE);
		serviceIsRunning = mySharedPrefs.getBoolean("serviceIsRunning",false);
		firstRunWarning = mySharedPrefs.getBoolean("firstRunWarning",true);
		runAtBoot = mySharedPrefs.getBoolean("runAtBoot", false);
//		wakeLock = mySharedPrefs.getBoolean("wakeLock", false);		
	}
	
    //-----------------------------
    //  Methods that actually start and stop the service
	//------------------------------	
	
    private void _startSvc(){
        try { 
            // setup and start MyService
            {

        		btn.setText("Stop the Fling Service");    
        	    serviceIsRunning = true;    
        		
            	FlingService.setMainActivity(this);              

            	svc.putExtra("onBoot", false);
            	startService(svc);
              
          
            }
          }
          catch (Exception e) {
        	  e.printStackTrace();
          }
    }

    private void _stopSvc(){
  	  {
  		btn.setText("Start the Fling Service");	  
  		
  	    //Intent svc = new Intent(this, FlingService.class);
  	    stopService(svc);
  	    serviceIsRunning = false;
  	    savePrefs();
  	  }
    }
    
}


